/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.pa036.hockeyStats;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 *
 * @author skvedo
 */
public class PictureSaver {

    @Resource(name = "jdbc/db")
    private static DataSource source;

    public static int storeImageToDB(int id, InputStream data, int dataLength) {
        Connection connection = null;
        PreparedStatement pst = null;
        try {
            connection = source.getConnection();
            pst = connection.prepareStatement(
                    "SELECT Photo FROM Person WHERE id=?");
            pst.setInt(1, id);
            ResultSet result = pst.executeQuery();
            boolean ret = result.next();
            if (!ret) {
                pst = connection.prepareStatement("INSERT INTO Person (Photo) VALUES (?)");
            } else {
                pst = connection.prepareStatement("UPDATE Person SET Photo=? WHERE id=?");
                pst.setInt(2, id);
            }
            int photoIndex = ret ? 1 : 2;
            pst.setBinaryStream(photoIndex, data, dataLength);
            pst.executeUpdate();            
        
        } catch (SQLException ex) {
            Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex1) {
                    Logger.getLogger(PictureLoader.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
                if (pst != null) {
                    pst.close();
                }
            } catch (SQLException ex) {
                Logger.getLogger(PictureLoader.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return 0;
    }
}
